# -*- coding: utf-8 -*-
import urllib2, json, sys, smtplib, random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from PIL import Image,ImageDraw,ImageFont
import time
# reload(sys)
# sys.setdefaultencoding('utf-8')  # 避免中文编码问题

mail_host = "smtp.nuaa.edu.cn"  # 设置发送邮件的服务器
mail_user = "****************"  # 用于发送邮件的邮箱用户名
mail_pass = "****************"  # 用于发送邮件的邮箱密码
mailto_list = ['ixingo@qq.com']  # 邮件接受者，list，可以设置多个邮件接收者

arr = ['听君一席话，胜读十年书。', '你的形象给了你高贵的个性', '你的语言给了你敏锐的头脑', '你的冷静给了你非凡的气质',
       '你是大家的活宝，你很酷！', '你很慈善！你很亲切！', '你很有气质，有内涵', '你到处散发的男人的魅力',
       '你让我越来越自信心', '你的个子长的象标准的模特', '你一天能工作十六个小时， 你真了不起',
       '人和名字一样美', '思想成熟、精明能干、为人诚实', '你这种学习精神是可以成为我的榜样', '你的发型是今年最流行的',
       '你的眼睛虽然是单眼皮，但那光很锐利，严肃中流露着柔和，冷酷中显示着热情',
       '你的气质很高雅', '你的确很有魅力', '你抽烟的样子象个知识分子', '您的语调独特，言谈话语中充满了感染力。']
#随机的一个字数串数组，生成邮件主题

def send_mail(to_list, part1, sub, content):
    # to_list：收件人；sub：主题；content：邮件内容;
    me = part1 + "<" + mail_user + ">"  # hello
    msg = MIMEText(content, _subtype='plain', _charset='utf-8')  # 创建一个实例，这里设置为纯文字格式邮件编码utf8
    msg['Subject'] = sub  # 设置主题
    msg['From'] = me  # 设置发件人
    msg['To'] = ";".join(to_list)
    try:
        s = smtplib.SMTP()  
        s.connect(mail_host)  # 连接smtp服务器
        s.login(mail_user, mail_pass)  # 登陆右键服务器
        s.sendmail(me, to_list, msg.as_string())  # 发送邮件
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False

def 

if __name__ == '__main__':
    appkey = "***************************"#申请的百度APIStore里的天气API Key
    url = 'http://apis.baidu.com/heweather/weather/free?city=luan'#get方法提交请求，城市的英文名
    req = urllib2.Request(url)
    req.add_header("apikey", appkey)
    resp = urllib2.urlopen(req)
    content = resp.read()
    if (content):
        json_result = json.loads(content)
        miaoshu = json_result['HeWeather data service 3.0'][0]['now']['cond']['txt']
        tigan = json_result['HeWeather data service 3.0'][0]['now']['fl']
        shidu = json_result['HeWeather data service 3.0'][0]['now']['hum']
        wendu = json_result['HeWeather data service 3.0'][0]['now']['tmp']
        fengxiang = json_result['HeWeather data service 3.0'][0]['now']['wind']['dir']
        fengli = json_result['HeWeather data service 3.0'][0]['now']['wind']['sc']
        day = json_result['HeWeather data service 3.0'][0]['daily_forecast'][1]['cond']['txt_d']
        night = json_result['HeWeather data service 3.0'][0]['daily_forecast'][1]['cond']['txt_n']

        font = ImageFont.truetype('Wyue-GutiFangsong-NC.otf',21)
    	newfont = ImageFont.truetype('msyhl.ttc',45)
        img = Image.open('hello.png')
        draw = ImageDraw.Draw(img)
        draw.text( (594,185),"南京".decode("GBK")(0,0,0),font=font)
        draw.text((782,185),miaoshu.decode("GBK"),(0,0,0),font=font) 
        draw.text((603,222),day.decode("GBK"),(0,0,0),font=font) 
        draw.text((855,222),night.decode("GBK"),(0,0,0),font=newfont)
        draw.text((292,375),tigan,(0,0,0),font=newfont) 
        draw.text((606,375),shidu,(0,0,0),font=newfont) 
        draw.text((918,375),fengli,(0,0,0),font=newfont) 
        timenow = (time.strftime("%Y年%m月%d日 %H时%M分",time.localtime(time.time()))).decode("GBK")
		nfont = ImageFont.truetype('msyhl.ttc',18)
		draw.text((944,678),timenow,(0,0,0),font=nfont) 
		img.save('天气预报.png')

        if send_mail(mailto_list, '汪欣', '早安老大,今天' + arr[random.randint(0, len(arr) - 1)],
                     "六安当前天气为" + miaoshu + ",预计白天" + day + ",夜间" + night + ",当前温度" + tigan + "摄氏度，湿度为:"
                             + shidu + ",风向:" + fengxiang + "，" + fengli + "级"):
            print "发送成功！"
        else:
            print "发送失败"
    else:
        print "程序错误"
